package com.review.util;

import java.sql.*;

/**
 * 建议
 * 1、url、name、password等都是不变的常量，应该用static final修饰
 * 2、写完代码可以格式化一下
 * 3、查询的getId方法，返回值为啥为void，返回ResultSet比较合适,打印应该是测试代码
 */
public class DataOperation {
    Connection con;
    Statement statement = null;
    //驱动程序名
    private final String driver = "com.mysql.jdbc.Driver";
    //URL指向要访问的数据库名mydata
    private final String url = "jdbc:mysql://101.201.239.71:3306/user";
    //MySQL配置时的用户名
    private final String user = "root";
    //MySQL配置时的密码
    private final String password = "951011";

    public void dataConnect() {
        //遍历查询结果集
        try {
            //加载驱动程序
            Class.forName(driver);
            //1.getConnection()方法，连接MySQL数据库！！
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("Succeeded connecting to the Database!");
                statement = con.createStatement();
            }
            //2.创建statement类对象，用来执行SQL语句！！;
            //要执行的SQL语句
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void getId() {
        String sql = "SELECT id FROM t_user";
        ResultSet resultSet = null;
        try {
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.println("查询" + resultSet.getInt("id"));
            }
            while (resultSet.next()) {
                resultSet.getInt("id");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean insert(String name, String password, String tel, String email) {
        String sql1 = "INSERT INTO t_user(user_name,user_password,telphone,email)" +
            "VALUES ('" + name + "','" + password + "','" + tel + "','" + email + "')";
        try {
            boolean a = statement.execute(sql1);
            return a;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public Boolean delete(int id) {
        String sql2 = "DELETE FROM t_user WHERE id=" + id;
        try {
            boolean a = statement.execute(sql2);
            return a;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public int update(int id, String name) {
        String sql3 = "UPDATE t_user set user_name='" + name + "'where id=" + id;
        try {
            int b = statement.executeUpdate(sql3);
            return b;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void main(String[] args) {
        new StringOperation();
    }
}

